package functionsVariables;

import java.io.Serializable;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;

public class MySQLConnection implements Serializable {

	private static final long serialVersionUID = 1L;

	// database URL
	private static final String M_DB_URL = "jdbc:mysql://localhost/";
	// String url = "jdbc:mysql://localhost:3306/";
	private static final String DB_NAME = "POIsDB";
	// User name
	private static final String M_DB_USER = "root";
	// Password
	private static final String M_DB_PASSWD = "";
	// Database engine name
	private static final String M_DB = "MySQL";
	// JDBC driver
	private static final String M_DBDRIVER_CLASS = "com.mysql.jdbc.Driver";

	private static Connection connection = null;
	
	private static MySQLConnection instance = null;

	/**
	 * ------------------------------------------------------------------------
	 * Constructor class
	 * ------------------------------------------------------------------------
	 */
	public synchronized static MySQLConnection getInstance() {
		if (instance==null)
			instance = new MySQLConnection();
		return instance;
	}
	
	/**
	 * ------------------------------------------------------------------------
	 * Opens the connection with MySQL
	 * ------------------------------------------------------------------------
	 */
	public synchronized Connection openConnection() {
		try {
			Class.forName(M_DBDRIVER_CLASS).newInstance();
			connection = (Connection) DriverManager.getConnection(M_DB_URL
					+ DB_NAME, M_DB_USER, M_DB_PASSWD);
			System.err.println("Connected to the database");
			return connection;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * ------------------------------------------------------------------------
	 * Closes the connection with MySQL
	 * ------------------------------------------------------------------------
	 */
	public synchronized void closeConnection() {
		if (connection != null) {
			try {
				((Connection) connection).close();
				System.err.println("Disconnected from database");
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static String getDBName() {
		return DB_NAME;
	}
	
	

}
